package org.study.event.core.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import com.google.common.base.Function;

/***
 * 工具类
 * 
 * @author 陈波
 *
 */
public  final class Maps {

	/***
	 * 键值对Pair对象
	 * 
	 * @author 陈波
	 *
	 * @param <K>
	 * @param <V>
	 */
	public final static class Pair<K, V> {
		private K key;
		private V value;

		public K getKey() {
			return key;
		}

		public V getValue() {
			return value;
		}

		private Pair(K key, V value) {
			super();
			this.key = key;
			this.value = value;
		}

	}

	/***
	 * 转换操作
	 * 
	 * @author lyf
	 * @param <M>
	 * @param <K>
	 * @param <V>
	 */
      public interface Covert<M, K, V> {
		public Pair<K, V> covertPair(M m);
	  }

	/***
	 * 转换Pair对象
	 * 
	 * @param entry
	 * @return
	 */
	public static <K, V> Pair<K, V> transforme(Map.Entry<K, V> entry) {
		return buildPair(entry.getKey(), entry.getValue());
	}

	public static <K, V> Pair<K, V> buildPair(K key, V value) {
		return new Pair<K, V>(key, value);
	}

	/***
	 * 提取Collection 中的数据转换成Map结构 ,使用Google guava Function对象
	 * 
	 * @param collections
	 * @param keyFunc
	 * @param valueFunc
	 * @return
	 */
	public static <K, M, V> Map<K, V> getMapFromCollection(Collection<M> collections,
			Function<? super M, ? extends K> keyFunc, Function<? super M, ? extends V> valueFunc) {

		if (!CollectionUtils.isEmpty(collections) || null == keyFunc || null == valueFunc) {
			throw new IllegalArgumentException(" arguments collections ,keyFunc,valueFunc is required! ");
		}

		Map<K, V> map = new HashMap<>(collections.size());

		for (Iterator<M> iterator = collections.iterator(); iterator.hasNext();) {
			M m = iterator.next();
			K k = keyFunc.apply(m);
			V v = valueFunc.apply(m);
			map.put(k, v);
		}

		return map;
	}

	/***
	 * 构造对象操作
	 * 
	 * @param collections
	 * @param covert
	 * @return
	 */
	public static <K, M, V> Map<K, V> getMapFromCollection(Collection<M> collections,
			Covert<? super M, ? extends K, ? extends V> covert) {
		if (!CollectionUtils.isEmpty(collections) || null == covert) {
			throw new IllegalArgumentException(" arguments collections ,covert is required! ");
		}
		Map<K, V> map = new HashMap<>(collections.size());
		Iterator<M> iterator = collections.iterator();
		while (iterator.hasNext()) {
			M m = iterator.next();
			Pair<? extends K, ? extends V> pair = covert.covertPair(m);
			map.put(pair.getKey(), pair.getValue());
		}
		return map;
	}

}
